package org.zgjy;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.zgjy.mapper.ModelMapper;
import org.zgjy.model.Device;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

@SpringBootApplication
public class DcserverApplication {

    public synchronized static void start_backend_services(){

        List<Device> devices;
        ModbusTimerTask.configs = new ArrayList<>();

        String fname = "src/main/resources/boot.properties";
        Path bootPath = Paths.get(fname);
        String bootContent;

        String filename = "src/main/resources/config/CL_FA201B.json";
        Path path = Paths.get(filename);
        String content;

        String resource = "mybatis_conf.xml";
        InputStream inputStream;
        SqlSessionFactory sqlSessionFactory;
        SqlSession session;
        ModelMapper mapper;
        DeviceConfig config;

        try{
            bootContent = Files.readString(bootPath);

            RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
            System.out.println("# RuntimeMXBean : " + runtimeMXBean.getName());
            String runtimeMXBeanName = runtimeMXBean.getName();
            if(bootContent!=null && bootContent.equals(runtimeMXBeanName)){
                return;
            }

            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            session = sqlSessionFactory.openSession();
            mapper = session.getMapper(ModelMapper.class);
            devices = mapper.selectDevice();
            content = Files.readString(path);
            config = JSON.parseObject(content, DeviceConfig.class);

            // 添加配置
            ModbusTimerTask.configs.add(config);
            ModbusTimerTask modbusTimerTask = new ModbusTimerTask("Task1", devices);

            Timer timer1 = new Timer();
            timer1.schedule(modbusTimerTask, 3L, 5000L);
            MqttService.add_message_source(modbusTimerTask);

            // 给 MqttService 装配消息源
//            MqttTimerTask.add_message_source(modbusTimerTask);
//            MqttTimerTask mqttTimerTask = new MqttTimerTask();
//            Timer timer2 = new Timer();
//            timer2.schedule(mqttTimerTask, 10L, 5000L);

            String strTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
            System.out.println("主线程:" + Thread.currentThread().getId() + " Time:" + strTime);

            Files.write(bootPath, runtimeMXBeanName.getBytes(), StandardOpenOption.WRITE);

        }catch (Exception e){
            System.out.println(e);
        }

    }

    public static void main(String[] args) {

        SpringApplication.run(DcserverApplication.class, args);

        // 各种类 会被 spring 重新载入内存， 随意必须在 spring 容器启动完成后，再来启动其他服务
        // org.springframework.boot.devtools.restart.classloader.RestartClassLoader
        start_backend_services();
    }

}
